<template>
  <div class="identity-verification">
    <div class="page-header">
      <h2 class="page-title">实名认证</h2>
      <p class="page-subtitle">完成实名认证，保障账户安全</p>
    </div>

    <!-- 认证状态卡片 -->
    <el-card class="status-card" shadow="hover" v-if="verificationStatus && verificationStatus.status">
      <el-result
        :icon="getStatusIcon(verificationStatus.status)"
        :title="getStatusTitle(verificationStatus.status)"
        :sub-title="getStatusSubtitle(verificationStatus.status)"
      >
        <template #extra>
          <el-descriptions :column="2" border v-if="verificationStatus.status === 'approved'">
            <el-descriptions-item label="真实姓名">
              {{ verificationStatus.realName }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ verificationStatus.idCardNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="人脸相似度">
              {{ verificationStatus.faceScore }}%
            </el-descriptions-item>
            <el-descriptions-item label="认证时间">
              {{ formatDate(verificationStatus.verifiedAt) }}
            </el-descriptions-item>
          </el-descriptions>
          <el-alert
            v-if="verificationStatus.status === 'rejected'"
            :title="verificationStatus.rejectionReason"
            type="error"
            :closable="false"
            style="margin-top: 20px"
          />
        </template>
      </el-result>
    </el-card>

    <!-- 认证表单 -->
    <el-card class="form-card" shadow="hover" v-if="!verificationStatus || !verificationStatus.status || verificationStatus.status === 'rejected'">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Document /></el-icon>
          <span>填写认证信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入与身份证一致的真实姓名"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="身份证号码" prop="idCardNumber">
          <el-input
            v-model="form.idCardNumber"
            placeholder="请输入18位身份证号码"
            maxlength="18"
            @blur="validateIdCard"
          />
          <div class="form-tip">请输入与身份证一致的18位身份证号码</div>
        </el-form-item>

        <el-form-item label="身份证正面" prop="idCardFront">
          <el-upload
            class="id-card-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleIdCardFrontChange"
            :accept="'image/*'"
            drag
          >
            <img v-if="idCardFrontPreview" :src="idCardFrontPreview" class="id-card-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击或拖拽上传身份证正面</div>
              <div class="upload-tip">支持 JPG、PNG 格式，文件大小不超过 5MB</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证反面" prop="idCardBack">
          <el-upload
            class="id-card-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleIdCardBackChange"
            :accept="'image/*'"
            drag
          >
            <img v-if="idCardBackPreview" :src="idCardBackPreview" class="id-card-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击或拖拽上传身份证反面</div>
              <div class="upload-tip">支持 JPG、PNG 格式，文件大小不超过 5MB</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="人脸照片" prop="faceImage">
          <el-upload
            class="face-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFaceImageChange"
            :accept="'image/*'"
            drag
          >
            <img v-if="faceImagePreview" :src="faceImagePreview" class="face-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><User /></el-icon>
              <div class="upload-text">点击或拖拽上传人脸照片</div>
              <div class="upload-tip">请上传清晰的正面照片，确保面部清晰可见</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="handleSubmit" size="large">
            <el-icon><Check /></el-icon>
            提交认证
          </el-button>
          <el-button @click="handleReset" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 认证说明 -->
    <el-card class="info-card" shadow="hover" style="margin-top: 24px">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><InfoFilled /></el-icon>
          <span>认证说明</span>
        </div>
      </template>
      <el-alert
        title="认证须知"
        type="info"
        :closable="false"
        show-icon
      >
        <ul class="info-list">
          <li>请确保上传的身份证照片清晰、完整，所有信息可见</li>
          <li>人脸照片需为本人正面清晰照片，与身份证照片一致</li>
          <li>身份证号码必须与上传的身份证照片信息一致</li>
          <li>认证信息提交后不可修改，请仔细核对</li>
          <li>认证审核通常在1-3个工作日内完成</li>
          <li>您的个人信息将被严格保密，仅用于身份验证</li>
        </ul>
      </el-alert>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Document, Plus, User, Check, InfoFilled } from '@element-plus/icons-vue'
import { identityApi } from '../api/identity'

const formRef = ref<FormInstance>()
const submitting = ref(false)
const verificationStatus = ref<any>(null)

const form = reactive({
  realName: '',
  idCardNumber: '',
  idCardFront: null as File | null,
  idCardBack: null as File | null,
  faceImage: null as File | null,
})

const idCardFrontPreview = ref('')
const idCardBackPreview = ref('')
const faceImagePreview = ref('')

const rules: FormRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  idCardNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '身份证号码格式不正确', trigger: 'blur' },
  ],
  idCardFront: [
    { required: true, message: '请上传身份证正面', trigger: 'change' },
  ],
  idCardBack: [
    { required: true, message: '请上传身份证反面', trigger: 'change' },
  ],
  faceImage: [
    { required: true, message: '请上传人脸照片', trigger: 'change' },
  ],
}

onMounted(() => {
  loadVerificationStatus()
})

const loadVerificationStatus = async () => {
  try {
    const status = await identityApi.getVerificationStatus()
    verificationStatus.value = status
  } catch (error: any) {
    console.error('获取认证状态失败:', error)
  }
}

const validateIdCard = () => {
  const idCard = form.idCardNumber
  if (!idCard) return
  
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  if (!reg.test(idCard)) {
    ElMessage.warning('身份证号码格式不正确')
  }
}

const handleIdCardFrontChange = (file: any) => {
  if (file.raw) {
    if (file.raw.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过 5MB')
      return
    }
    form.idCardFront = file.raw
    const reader = new FileReader()
    reader.onload = (e) => {
      idCardFrontPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
}

const handleIdCardBackChange = (file: any) => {
  if (file.raw) {
    if (file.raw.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过 5MB')
      return
    }
    form.idCardBack = file.raw
    const reader = new FileReader()
    reader.onload = (e) => {
      idCardBackPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
}

const handleFaceImageChange = (file: any) => {
  if (file.raw) {
    if (file.raw.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过 5MB')
      return
    }
    form.faceImage = file.raw
    const reader = new FileReader()
    reader.onload = (e) => {
      faceImagePreview.value = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    if (!form.idCardFront || !form.idCardBack || !form.faceImage) {
      ElMessage.error('请上传所有必需的图片')
      return
    }

    try {
      await ElMessageBox.confirm(
        '确认提交实名认证？提交后信息不可修改，请仔细核对。',
        '确认提交',
        {
          confirmButtonText: '确认提交',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )

      submitting.value = true
      const result = await identityApi.verifyIdentity({
        realName: form.realName,
        idCardNumber: form.idCardNumber,
        idCardFront: form.idCardFront!,
        idCardBack: form.idCardBack!,
        faceImage: form.faceImage!,
      })

      ElMessage.success(result.message || '认证提交成功！')
      await loadVerificationStatus()
      handleReset()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '提交失败，请重试')
      }
    } finally {
      submitting.value = false
    }
  })
}

const handleReset = () => {
  formRef.value?.resetFields()
  form.idCardFront = null
  form.idCardBack = null
  form.faceImage = null
  idCardFrontPreview.value = ''
  idCardBackPreview.value = ''
  faceImagePreview.value = ''
}

const getStatusIcon = (status: string | null) => {
  if (!status) return 'info'
  const icons: Record<string, any> = {
    pending: 'clock',
    processing: 'loading',
    approved: 'success',
    rejected: 'error',
  }
  return icons[status] || 'info'
}

const getStatusTitle = (status: string | null) => {
  if (!status) return '未认证'
  const titles: Record<string, string> = {
    pending: '认证待审核',
    processing: '认证审核中',
    approved: '认证已通过',
    rejected: '认证已拒绝',
  }
  return titles[status] || '未知状态'
}

const getStatusSubtitle = (status: string | null) => {
  if (!status) return '您尚未提交实名认证，请填写信息完成认证'
  const subtitles: Record<string, string> = {
    pending: '您的认证信息已提交，请耐心等待审核',
    processing: '我们正在审核您的认证信息，请稍候',
    approved: '恭喜！您的实名认证已通过',
    rejected: '您的认证信息未通过审核，请重新提交',
  }
  return subtitles[status] || '状态异常，请联系客服'
}

const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}
</script>

<style scoped>
.identity-verification {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.status-card {
  margin-bottom: 24px;
}

.form-card {
  margin-bottom: 24px;
}

.info-card {
  margin-top: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.id-card-uploader,
.face-uploader {
  width: 100%;
}

.id-card-uploader :deep(.el-upload),
.face-uploader :deep(.el-upload) {
  width: 100%;
}

.id-card-uploader :deep(.el-upload-dragger),
.face-uploader :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.id-card-uploader :deep(.el-upload-dragger:hover),
.face-uploader :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
}

.id-card-image,
.face-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  border-radius: 6px;
}

.info-list {
  margin: 10px 0 0 0;
  padding-left: 20px;
}

.info-list li {
  margin-bottom: 8px;
  line-height: 1.6;
}
</style>






